package com.wangl.spring.contributor.completionContributor;

import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.lang.properties.IProperty;
import com.intellij.lang.properties.psi.PropertiesFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.ProcessingContext;
import com.wangl.spring.service.SuggestionService;
import com.wangl.spring.utils.Icons;
import com.wangl.spring.utils.PsiCustomUtil;
import com.wangl.spring.utils.StringPropertiesUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @ClassName PropertyCompletionProvider
 * @Description TODO
 * @Author wangl
 * @Date 2023/3/24 14:10
 */
public class PropertyCompletionProvider extends CompletionProvider<CompletionParameters> {
    @Override
    protected void addCompletions(@NotNull CompletionParameters parameters,
                                  @NotNull ProcessingContext context,
                                  @NotNull CompletionResultSet result) {

        // 获取用户输入的前缀
        PsiElement position = parameters.getPosition();
        int length = CompletionUtilCore.DUMMY_IDENTIFIER.length();
        String text = position.getText();
        String originText = text.substring(0, text.length() - length + 1);
        String prefix = originText.replaceAll("\\[\\d*\\]", "");
        // 如果前缀为空白字符，则不进行任何操作
        if (prefix.trim().isEmpty()) {
            return;
        }
        // 自定义前缀匹配器
        result = result.withPrefixMatcher(new CustomPrefixMatcher(originText));
        // 获取所有建议
        SuggestionService service = PsiCustomUtil.findModule(position).getService(SuggestionService.class);
        if (!service.isCanSuggest()){
            return;
        }
        List<String> suggestions = service.getSuggestionsByPrefix(prefix);
        PsiFile psiFile = position.getContainingFile();
        Set<String> existsProperties = new HashSet<>();
        if (psiFile instanceof PropertiesFile){
            PropertiesFile propertiesFile = (PropertiesFile) psiFile;
            List<IProperty> properties = propertiesFile.getProperties();
            for (IProperty property : properties) {
                existsProperties.add(StringPropertiesUtil.kebabCaseToCamelCase(property.getKey()));
            }
        }
        // 添加匹配结果
        for (String suggestion : suggestions) {
            if (suggestion.contains(".")){
                suggestion = originText.substring(0, originText.lastIndexOf(".")) + suggestion.substring(suggestion.lastIndexOf("."));
            }
            if (existsProperties.contains(StringPropertiesUtil.kebabCaseToCamelCase(suggestion))){
                continue;
            }

            LookupElement element = LookupElementBuilder.create(suggestion)
                    .withIcon(Icons.leaf)
                    .withCaseSensitivity(false);
            result.addElement(element);
        }
    }

    public static class CustomPrefixMatcher extends PrefixMatcher {
        public CustomPrefixMatcher(String s) {
            super(s);
        }

        @Override
        public boolean prefixMatches(@NotNull String name) {
            if (myPrefix.isEmpty() || myPrefix.endsWith(".")) {
                return true;
            }
            return name.contains(myPrefix);
        }

        @Override
        public @NotNull PrefixMatcher cloneWithPrefix(@NotNull String prefix) {
            return new CustomPrefixMatcher(prefix);
        }
    }
}
